<?php


namespace App\Http\Controllers\Core;


use App\Services\Core\Curd\CurdServicesProvider;
use App\Services\Core\Traits\Response;
use App\Services\Core\Traits\Validator;

class AdminBaseController extends Controller
{
    use Response, Validator;

    protected $curdServices;

    protected $request;

    protected $result;

    protected array $writeData = [];

    public function __construct($model = null)
    {
        $this->curdServices = new CurdServicesProvider($model);

        $this->curdServices->limit = 10;

        $this->request = \request();
    }

    public function select()
    {
        $this->selectBefore();

        $this->result = $this->curdServices->setPagination($this->request->all())->select();

        $this->selectAfter();

        return $this->success([
            'list'       => $this->result,
            'pagination' => $this->curdServices->getPagination()
        ]);
    }

    public function all()
    {

        $this->allBefore();

        $this->result = $this->curdServices->all();

        $this->allAfter();

        return $this->success($this->result);
    }

    public function find()
    {
        $this->findBefore();

        $this->result = $this->curdServices->find(isset($this->writeData['id']) ? $this->writeData['id'] : $this->request->get('id'));

        if (!$this->result) $this->fail(msg: '目标不存在');

        $this->findAfter();

        return $this->success($this->result);
    }

    public function create()
    {
        $this->createBefore();

        if(empty($this->writeData)) $this->fail(msg:'请设置写入数据');

        $this->result = $this->curdServices->create($this->writeData);

        $this->createAfter();

        return $this->success($this->result);
    }

    public function save()
    {
        $this->saveBefore();

        $this->result = $this->curdServices->save(!empty($this->writeData) ? $this->writeData : $this->request->all());

        $this->saveAfter();

        return $this->success();
    }

    public function destroy()
    {
        $this->destroyBefore();

        $this->result = $this->curdServices->destroy();

        $this->destroyAfter();

        return $this->result ? $this->success() : $this->fail();
    }

    public function batchDestroy()
    {
        $this->batchDestroyBefore();

        $this->result = $this->curdServices->batchDestroy();

        $this->batchDestroyAfter();

        return $this->result ? $this->success() : $this->fail();
    }

    protected function getAdminInfo(string $key = '')
    {
        return '' === $key ? $this->request->get('admin') : $this->request->get('admin')[$key];
    }
}
